class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy, :update_user_trainee_title]

  def personal_center
    @html_title = ts(:personal, :center)
    @course_objects = current_user.course_objects.created_at_desc.limit(6)
    @course_learning_records = current_user.course_learning_records.created_at_desc.includes([:course_object]).limit(6)
    if @course_objects.present?
      @my_teaching_chat
    end
  end

  # GET /users
  # GET /users.json
  def index
    @html_title ||= ts(User, :list)
    @search = User.ransack params[:q]
    @users = @search.result.includes(:trainee_title).page(params[:page]||1).per(per_page)
  end

  def user_trainee_title_index
    @html_title = ts :teacher_training, :settings
    @trainee_title_options = Trainee::Title.options_for_select
    @search = User.ransack params[:q]
    @users = @search.result.page(params[:page]||1).per(per_page)
  end

  def update_user_trainee_title
    @user.trainee_title_id = params[:trainee_title_id]
    @user.save
    respond_to do |format|
      format.js
    end
  end

  # GET /users/1
  # GET /users/1.json
  def show
    @html_title ||= ts User, :detail
    render layout: 'modal'
  end

  # GET /users/new
  def new
    @user = User.new
    render layout: 'modal'
  end

  # GET /users/1/edit
  def edit
    @html_title ||= ts :edit, User
    render layout: 'modal'
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    if @user.save
      show_js_notice('创建成功！')
    else
      error_notice(@user)
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    if @user.update(user_params)
      show_js_notice('修改成功！')
    else
      error_notice(@user)
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    show_js_notice('删除成功！')
    # respond_to do |format|
    #   format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
    #   format.json { head :no_content }
    # end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:active, :school_id, :school_ids, :trainee_title_id, :role_type)
    end
end
